package com.link.base.wechat.wxmenu.util;

import com.alibaba.fastjson.JSONObject;
import com.link.base.wechat.basic.util.WeixinHttpUtil;
import com.link.base.wechat.basic.util.WxExceptionUtil;
import com.link.base.wechat.wxcard.util.WxCardUtil;
import com.link.base.wechat.wxmenu.model.WxMenu;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.StringUtils;

/**
 * 微信公众号自定义菜单工具类
 *
 * @author lujiang
 * @date 2019/02/25 17:00
 */
public class WxMenuUtil {
    /**
     * 微信公众号自定义菜单创建请求服务器路径
     */
    public static final String MENU_CREATE_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
    /**
     * 清空自定义菜单
     */
    public static final String DELETE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";

    /**
     * 微信公众号自定义菜单创建，修改，删除二级菜单
     *
     * @author lujiang
     * @date 2019/02/25 17:13
     * @param accessToken 全局唯一接口调用凭据
     * @param wxMenu 自定义菜单对象
     */
    public static int upsertWxMenu(String accessToken, WxMenu wxMenu) throws Exception {

        if (StringUtils.isBlank(accessToken)) {
            throw new ServiceException("WXMENU-001");
        }
        String requestUrl = MENU_CREATE_URL.replace("ACCESS_TOKEN", accessToken);
        // 驼峰转下划线
        String jsonMenu = WxCardUtil.getJsonData(wxMenu);
        JSONObject jsonObject = WeixinHttpUtil.httpRequest(requestUrl, "POST", jsonMenu);
        WxExceptionUtil.parse(jsonObject.toJSONString());
        int result = 1;
        return result;
    }

    /**
     * 微信公众号自定义菜单清空
     *
     * @author lujiang
     * @date 2019/02/25 17:15
     * @param accessToken 全局唯一接口调用凭据
     */
    public static int clearWxMenu(String accessToken) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new ServiceException("WXMENU-001");
        }
        String requestUrl = DELETE_MENU_URL.replace("ACCESS_TOKEN", accessToken);
        JSONObject jsonObject = WeixinHttpUtil.httpRequest(requestUrl, "GET", null);
        WxExceptionUtil.parse(jsonObject.toJSONString());
        int result = 1;
        return result;
    }

}
